package com.wzq.upms.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.wzq.framework.util.UtilValidate;
import com.wzq.permission.client.model.EasyUiTree;
import com.wzq.permission.client.model.Pager;
import com.wzq.permission.client.model.admin.ApplicationUserModel;
import com.wzq.permission.client.model.admin.OrganizeModel;
import com.wzq.permission.client.model.admin.OrganizeRoleModel;
import com.wzq.permission.client.model.admin.RoleMenuModel;
import com.wzq.permission.client.model.admin.RoleModel;
import com.wzq.permission.client.model.admin.UserModel;
import com.wzq.permission.client.model.admin.UserOrganizeModel;
import com.wzq.permission.client.model.admin.UserRoleModel;
import com.wzq.permission.client.service.ApplicationService;
import com.wzq.permission.client.service.OrganizeService;
import com.wzq.permission.client.service.UserService;
import com.wzq.permission.client.utils.TreeUtil;
import com.wzq.upms.core.EasyUiData;
import com.wzq.upms.core.JsonResponse;
import com.wzq.upms.core.SessionUtils;

@Controller
@RequestMapping("organize")
public class OrganizeController {
	@Autowired
	private OrganizeService organizeServiceClient;
	@Autowired
	private ApplicationService applicationServiceClient;
	@Autowired
	private UserService userServiceClient;
	
	private static final Long applicationId = 1L;
	/**
	 * 用户页面
	 */
	private static final String APPLICATION_VIEW = "organize/organize";
	
	@Value("${app.key}")
	private String appKey;
	
	/**
	 * 用户页面
	 * @param model 模型对象
	 * @param request request对象
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping("/list") 
	public ModelAndView  list(OrganizeModel model,HttpServletRequest request) throws Exception{
		ModelAndView mv = new ModelAndView(APPLICATION_VIEW);
		request.setAttribute("applicationId", applicationId);
		return mv;
	}
	
	/**
	 * 获取数据列表
	 * @param model 模型对象
	 * @param pager 分页对象
	 * @return EasyUiData
	 * @throws Exception
	 */
	@RequestMapping("/dataList") 
	@ResponseBody
	public EasyUiData<UserOrganizeModel> dataList(UserOrganizeModel model,Pager pager,Long applicationId) throws Exception{
		EasyUiData<UserOrganizeModel> data = new EasyUiData<UserOrganizeModel>();
		List<UserOrganizeModel> result = new ArrayList<UserOrganizeModel>();
		if(StringUtils.isNotEmpty(model.getOrganizeName())){
			model.setOrganizeName("%"+model.getOrganizeName()+"%");
			model.setOrganizeId(null);
		} else {
			model.setOrganizeName(null);
		}
		int total =organizeServiceClient.queryUserOrgByCount(model);
		List<UserOrganizeModel> userOrgList = organizeServiceClient.queryUserOrgList(model, pager);
		result.addAll(userOrgList);
		data.setTotal(total);
		data.setRows(result==null?new ArrayList<UserOrganizeModel>():result);
		return data;
	}
	

	
	/**
	 * 获取用户列表
	 * @param model 模型对象
	 * @param pager 分页对象
	 * @return EasyUiData
	 * @throws Exception
	 */
	@RequestMapping("/userList") 
	@ResponseBody
	public EasyUiData<UserModel>  userList(UserModel model,Pager pager) throws Exception{
		EasyUiData<UserModel> data = new EasyUiData<UserModel>();
		List<UserModel> userLst = userServiceClient.queryList(model, pager);
		data.setTotal(userServiceClient.queryByCount(model));
		data.setRows(userLst==null?new ArrayList():userLst);
		return data;
	}
	
	/**
	 * 查询组织下的用户
	 * @param userId 用户ID
	 * @return 
	 */
	@RequestMapping("/queryOrgUser")
	@ResponseBody
	public List<UserOrganizeModel> queryOrgUser(Long organizeId){
		UserOrganizeModel model = new UserOrganizeModel();
		model.setOrganizeId(organizeId);
		List<UserOrganizeModel> userOrgList = organizeServiceClient.queryUserOrgList(model, null);
		return userOrgList;
	}
	
	/**
	 * 分配角色
	 * @param userId 用户ID
	 * @param applicationId 系统ID
	 * @param roleIds 角色ID集合
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addUser")
	@ResponseBody
	public JsonResponse addUser(Long organizeId,Long[] userIds,HttpServletRequest request)throws Exception{
		JsonResponse response = new JsonResponse(JsonResponse.SUCCESS,"添加用户成功");
		if(userIds!=null && userIds.length>0){
			UserModel user = SessionUtils.getUser(request);
			List<UserOrganizeModel> userOrgModelList = new ArrayList<UserOrganizeModel>();
			for(Long userId:userIds){
				UserOrganizeModel userOrgModel = new UserOrganizeModel();
				userOrgModel.setOrganizeId(organizeId);
				userOrgModel.setUserId(userId);
				userOrgModel.setCreateUser(user.getUserName());
				userOrgModel.setUpdateUser(user.getUserName());
				userOrgModelList.add(userOrgModel);
			}
			organizeServiceClient.addUser(userOrgModelList);
		}
		return response;
	} 
	
	/**
	 * 删除数据
	 * @param userIds 主键列表
	 * @param response 
	 * @throws Exception
	 */
	@RequestMapping("/deleteUser")
	@ResponseBody
	public JsonResponse deleteUser(Long[] userOrganizeIds) throws Exception{
		JsonResponse response = new JsonResponse(JsonResponse.SUCCESS,"删除成功");
		organizeServiceClient.deleteUser(userOrganizeIds);
		return response;
	}
	
	/**
	 * 删除组织
	 * @param organizeIds
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/deleteOrganize")
	@ResponseBody
	public JsonResponse deleteOrganize(Long organizeId) throws Exception{
		JsonResponse response = new JsonResponse(JsonResponse.SUCCESS,"删除成功");
		organizeServiceClient.deleteOrganize(organizeId);
		return response;
	}
	
	
	/**
	 * 根据ID查找对象
	 * @param menuId
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/getById")
	@ResponseBody
	public OrganizeModel getById(Long orgId) throws Exception{
		OrganizeModel model = organizeServiceClient.queryById(orgId);
		return model;
	}
	
	/**
	 * 添加或修改数据
	 * @param model 模型对象
	 * @throws Exception
	 */
	@RequestMapping("/add")
	@ResponseBody
	public JsonResponse add(OrganizeModel model,HttpServletRequest request) throws Exception{
		JsonResponse response = new JsonResponse(JsonResponse.SUCCESS,"保存成功");
		OrganizeModel tempOrganize = new OrganizeModel();
        tempOrganize.setParentId(model.getParentId());
        tempOrganize.setOrganizeName(model.getOrganizeName());
		if(organizeServiceClient.isExist(tempOrganize)>0){
		    response.setMsg("该组织已存在,请重新输入");
            response.setResult(JsonResponse.FAIL);
		}else{
		    UserModel user = SessionUtils.getUser(request);
	        model.setCreateUser(user.getUserName());
	        model.setUpdateUser(user.getUserName());
	        organizeServiceClient.add(model);
		}
		return response;
	}
	
	/**
	 * 添加或修改数据
	 * @param model 模型对象
	 * @throws Exception
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public JsonResponse edit(OrganizeModel model,HttpServletRequest request) throws Exception{
		JsonResponse response = new JsonResponse(JsonResponse.SUCCESS,"修改成功");
		OrganizeModel tempOrganize = new OrganizeModel();
		tempOrganize.setParentId(model.getParentId());
		tempOrganize.setOrganizeName(model.getOrganizeName());
		tempOrganize.setOrganizeId(model.getOrganizeId());
		if(organizeServiceClient.isExist(tempOrganize)>0){
            response.setMsg("该组织已存在,请重新输入");
            response.setResult(JsonResponse.FAIL);
        }else{
            UserModel user = SessionUtils.getUser(request);
            model.setUpdateTime(new Date());
            model.setCreateUser(user.getUserName());
            model.setUpdateUser(user.getUserName());
            organizeServiceClient.updateBySelective(model);
        }
		return response;
	}
	
	/**
	 * 菜单树
	 * @param applicationId
	 * @return
	 */
	@RequestMapping("/menuTree")
	@ResponseBody
	public List<EasyUiTree> menuTree(Long applicationId){
		List<OrganizeModel> orgList = organizeServiceClient.queryMenuTree();
		EasyUiTree root = new EasyUiTree();
		for(OrganizeModel orgModel:orgList){
			if(orgModel.getParentId()==-1){
				root.setId(orgModel.getOrganizeId());
				root.setText(orgModel.getOrganizeName());
			}
		}
		List<OrganizeModel> orgTreeList = TreeUtil.orgListToTree(orgList);
		List<EasyUiTree> treeList = TreeUtil.orgModelListToEasyUiTree(orgTreeList);
		List<EasyUiTree> result = new ArrayList<EasyUiTree>();
		root.setChildren(treeList);
		result.add(root);
		return result;
	}
	
	/**
	 * 角色树
	 * @param applicationId
	 * @return
	 */
	@RequestMapping("/roleTree")
	@ResponseBody
	public List<EasyUiTree> roleTree(Long applicationId){
		List<OrganizeRoleModel> orgList = organizeServiceClient.queryRoleTree();
		EasyUiTree root = new EasyUiTree();
		root.setId(-1l);
		root.setText("角色");
		List<OrganizeRoleModel> orgTreeList = TreeUtil.roleListToTree(orgList);
		List<EasyUiTree> treeList = TreeUtil.orgRoleListToEasyUiTree(orgTreeList);
		List<EasyUiTree> result = new ArrayList<EasyUiTree>();
		root.setChildren(treeList);
		result.add(root);
		return result;
	}
	
	/**
	 * 获取角色ID
	 * @param roleIds 主键列表
	 * @param response 
	 * @throws Exception
	 */
	@RequestMapping("/getRoleIdByOrgId")
	@ResponseBody
	public List<String> getRoleIdByOrgId(Long organizeId) throws Exception{
	
		List<String> result = organizeServiceClient.getRoleIdByOrgId(organizeId);
		return result;
	}
	
	/**
	 * 角色授权保存
	 * @param organizeId 主键列表
	 * @param response 
	 * @throws Exception
	 */
	@RequestMapping("/distribution")
	@ResponseBody
	public JsonResponse distributionSave(Long organizeId,String roleId,HttpServletRequest request) throws Exception{
		
		JsonResponse response = new JsonResponse(JsonResponse.SUCCESS,"角色配置成功");
		String[] roleIds={};
		if(UtilValidate.isNotEmpty(roleId)){//截取菜单的id
			roleIds=roleId.split(",");
		}
		
		List<OrganizeRoleModel> orgRoleList=new ArrayList<OrganizeRoleModel>();
		UserModel role = SessionUtils.getUser(request);
		
		for (int i = 0; i < roleIds.length; i++) {//添加菜单记录
			OrganizeRoleModel orgRole=new OrganizeRoleModel();
			orgRole.setRoleId(Long.valueOf(roleIds[i]));
			orgRole.setOrganizeId(organizeId);
			orgRole.setCreateTime(new Date());
			orgRole.setUpdateTime(new Date());
			orgRole.setCreateUser(role.getUserName());
			orgRole.setUpdateUser(role.getUserName());
			orgRoleList.add(orgRole);
		}
		organizeServiceClient.distributionSave(organizeId,orgRoleList);
	
		return response;
	}
}
